<!-- eslint-disable vue/valid-v-model -->
<template>
  <div>
    <el-card class="box-card">
      <div class="ele-page-header">
        <div class="ele-page-title">支付配置</div>
        <div class="ele-page-desc"> 用于支付参数配置 </div>
      </div>

      <div style="margin-top: 30px">
        <el-row :gutter="10"
                type="flex"
                class="row-bg"
                justify="center">
          <el-col :span="12">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="支付类型:"
                            label-width="150px"
                            prop="payType">
                <el-radio-group v-model.trim="form.payType">
                  <el-radio label="1"
                            value="1">微信支付</el-radio>
                  <el-radio label="2"
                            value="2">微信服务商支付</el-radio>
                </el-radio-group>
              </el-form-item>
              <div v-if="form.payType == 2">
                <!-- <el-form-item label="商户appid"
                              label-width="150px"
                              prop="fwsWxAppid">
                  <el-input clearable
                            :maxlength="100"
                            v-model.trim="form.fwsWxAppid"
                            placeholder="请输入商户appid">
                  </el-input>
                </el-form-item> -->
                <el-form-item label="商户号:"
                              label-width="150px"
                              prop="fwsMchId">
                  <el-input clearable
                            :maxlength="100"
                            v-model.trim="form.fwsMchId"
                            placeholder="请输入商户号">
                  </el-input>
                </el-form-item>
                <el-form-item label="子商户号:"
                              label-width="150px"
                              prop="fwsPtMchId">
                  <el-input clearable
                            v-model.trim="form.fwsPtMchId"
                            placeholder="请输入子商户号" />
                </el-form-item>
                <el-form-item label="小程序appid:"
                              label-width="150px"
                              prop="fwsXcxAppid">
                  <el-input clearable
                            :maxlength="100"
                            v-model.trim="form.fwsXcxAppid"
                            placeholder="请输入小程序appid">
                  </el-input>
                </el-form-item>

                <el-form-item label="小程序AppSecret:"
                              label-width="150px"
                              prop="fwsXcxAppsecret">
                  <el-input clearable
                            show-password
                            :maxlength="100"
                            v-model.trim="form.fwsXcxAppsecret"
                            placeholder="请输入小程序AppSecret">
                  </el-input>
                </el-form-item>

                <!-- <el-form-item label="小程序openid:"
                          label-width="150px"
                          prop="fwsXcxOpenId">
              <el-input clearable
                        v-model="form.fwsXcxOpenId"
                        placeholder="请输入小程序openid" />
            </el-form-item> -->
                <el-form-item label="公众号appid:"
                              label-width="150px"
                              prop="fwsGzhAppid">
                  <el-input clearable
                            v-model.trim="form.fwsGzhAppid"
                            placeholder="请输入公众号appid" />
                </el-form-item>
                <el-form-item label="公众号Appsecret:"
                              label-width="150px"
                              prop="fwsGzhAppsecret">
                  <el-input clearable
                            show-password
                            v-model.trim="form.fwsGzhAppsecret"
                            placeholder="请输入公众号Appsecret" />
                </el-form-item>
                <!-- <el-form-item label="公众号openid:"
                          label-width="150px"
                          prop="fwsGzhOpenId">
              <el-input clearable
                        v-model="form.fwsGzhOpenId"
                        placeholder="请输入公众号openid" />
            </el-form-item> -->

                <el-form-item label="支付v3密钥:"
                              label-width="150px"
                              prop="fwsV3Key">
                  <el-input clearable
                            show-password
                            v-model.trim="form.fwsV3Key"
                            placeholder="请输入支付v3密钥" />
                </el-form-item>
                <el-form-item label="支付私钥:"
                              label-width="150px"
                              prop="fwsPrivateKey">
                  <el-input clearable
                            show-password
                            @change="(e) => filterText(e, 'wxForm')"
                            v-model.trim="form.fwsPrivateKey"
                            placeholder="请输入支付私钥" />
                </el-form-item>
              </div>
              <div v-if="form.payType == 1">
                <el-form-item label="小程序appid:"
                              label-width="150px"
                              prop="wxzfXcxAppid">
                  <el-input clearable
                            :maxlength="100"
                            v-model.trim="form.wxzfXcxAppid"
                            placeholder="请输入小程序appid">
                  </el-input>
                </el-form-item>
                <!-- <el-form-item label="支付小程序openid:"
                          label-width="150px"
                          prop="wxzfXcxOpenId">
              <el-input clearable
                        :maxlength="100"
                        v-model="form.wxzfXcxOpenId"
                        placeholder="请输入支付小程序openid">
              </el-input>
            </el-form-item> -->
                <el-form-item label="小程序appsecret:"
                              label-width="150px"
                              prop="wxzfXcxAppsecret">
                  <el-input clearable
                            :maxlength="100"
                            show-password
                            v-model.trim="form.wxzfXcxAppsecret"
                            placeholder="请输入小程序appsecret">
                  </el-input>
                </el-form-item>
                <el-form-item label="公众号appid:"
                              label-width="150px"
                              prop="wxzfGzhAppid">
                  <el-input clearable
                            :maxlength="100"
                            v-model.trim="form.wxzfGzhAppid"
                            placeholder="请输入公众号appid">
                  </el-input>
                </el-form-item>
                <el-form-item label="公众号appsecret:"
                              label-width="150px"
                              prop="wxzfGzhAppsecret">
                  <el-input clearable
                            :maxlength="100"
                            show-password
                            v-model.trim="form.wxzfGzhAppsecret"
                            placeholder="请输入公众号appsecret">
                  </el-input>
                </el-form-item>
                <!-- <el-form-item label="支付公众号openid:"
                          label-width="150px"
                          prop="wxzfGzhOpenId">
              <el-input clearable
                        :maxlength="100"
                        v-model="form.wxzfGzhOpenId"
                        placeholder="请输入支付公众号openid">
              </el-input>
            </el-form-item> -->
                <el-form-item label="支付商户号:"
                              label-width="150px"
                              prop="wxzfMchId">
                  <el-input clearable
                            v-model.trim="form.wxzfMchId"
                            placeholder="请输入支付商户号" />
                </el-form-item>
                <el-form-item label="支付v3密钥:"
                              label-width="150px"
                              prop="wxzfV3Key">
                  <el-input clearable
                            show-password
                            v-model.trim="form.wxzfV3Key"
                            placeholder="请输入支付v3密钥" />
                </el-form-item>
                <!-- <el-form-item label="微信支付appid:"
                              label-width="150px"
                              prop="wxzfWxAppid">
                  <el-input clearable
                            v-model.trim="form.wxzfWxAppid"
                            placeholder="请输入支付appid" />
                </el-form-item> -->
                <el-form-item label="支付私钥:"
                              label-width="150px"
                              prop="wxzfPrivateKey">
                  <el-input clearable
                            show-password
                            @change="(e) => filterText(e, 'wxServiceForm')"
                            v-model.trim="form.wxzfPrivateKey"
                            placeholder="请输入支付私钥" />
                </el-form-item>
              </div>
              <el-form-item label="打款类型:"
                            label-width="150px"
                            prop="name">
                <el-radio-group v-model.trim="form.remitType">
                  <!-- <el-radio label='1'
                        value='1'>企业付款到零钱</el-radio> -->
                  <el-radio label="1"
                            value="1">商家转账到零钱</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="证书序列号:"
                            label-width="150px"
                            prop="wxzfMerchantSerialNumber">
                <el-input v-if="form.payType == '1'"
                          clearable
                          v-model.trim="form.wxzfMerchantSerialNumber"
                          placeholder="请输入微信证书序列号" />
                <el-input v-else
                          clearable
                          v-model.trim="form.fwsMerchantSerialNumber"
                          placeholder="请输入服务商证书序列号" />
              </el-form-item>
              <el-form-item label="cert文件:"
                            label-width="150px"
                            prop="cert">
                <el-upload class="upload-demo"
                           drag
                           :limit="1"
                           :on-exceed="exceedFn"
                           :auto-upload="false"
                           :file-list='(form.payType==1)? fileWxzfCertList:fileFwsfCertList'
                           :on-remove="(e)=>handleRemove(e,(form.payType==1)? 'fileWxzfCertList':'fileFwsfCertList')"
                           :on-change="
                    (files, fileList) =>
                      handleFileChange(
                        files,
                        fileList,
                        form.payType == '1' ? 'wxzfCertFile' : 'fwsCertFile'
                      )
                  "
                           action="#">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip"
                       slot="tip">只能上传cert/pem文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
              <el-form-item label="key文件:"
                            label-width="150px"
                            prop="key">
                <el-upload class="upload-demo"
                           drag
                           :limit="1"
                           :file-list='(form.payType==1)? fileWxzfKeyList:fileFwsfKeyList'
                           :on-exceed="exceedFn1"
                           :on-remove="(e)=>handleRemove2(e,(form.payType==1)? 'fileWxzfKeyList':'fileFwsfKeyList')"
                           :auto-upload="false"
                           :on-change="
                    (files, fileList) =>
                      handleFileChange(
                        files,
                        fileList,
                        form.payType == '1' ? 'wxzfKeyFile' : 'fwsKeyFile'
                      )
                  "
                           action="#"
                           multiple>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip"
                       slot="tip">只能上传cert/key文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
              <el-form-item label-width="150px"
                            label="">
                <el-button type="primary"
                           :loading="loading"
                           @click="save">
                  保存更改
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>
<script>
import request from '@/utils/request';
import {
  sitePayConfigModify,
  sitePayConfigDetail,
  sitePayConfigsAdd
} from '@/api/basicConfiguration/paymentConfiguration/index';
import { getToken } from '@/utils/token-util';
import {
  userOssSignature,
  qnyOssSignature
} from '@/api/creatCenter/material';
import axios from 'axios';
export default {
  name: 'RoleEdit',
  components: {},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data () {
    const DEFAULT_FORM = {
      // 支付类型 1 微信支 2 微信服务商
      payType: '1',

      // 微信支付小程序appid
      wxzfXcxAppid: '',
      // 微信支付小程序appsecret
      wxzfXcxAppsecret: '',
      // 微信支付商户号
      wxzfMchId: '',
      // 微信支付支付密钥
      wxzfPrivateKey: '',
      //   微信支付小程序openid
      //   wxzfXcxOpenId: '',
      //    微信支付公众号appid
      wxzfGzhAppid: '',
      //微信支付公众号openid
      //   wxzfGzhOpenId: '',
      //微信支付公众号appsecret
      wxzfGzhAppsecret: '',
      // 微信支付v3密钥
      wxzfV3Key: '',
      // 微信支付appid
      //   wxzfWxAppid: '',
      // 微信支付证书序列号
      wxzfMerchantSerialNumber: '',
      //微信支付cert(证书)文件
      wxzfCertFile: '',
      // 微信支付key文件
      wxzfKeyFile: '',

      //  打款类型
      remitType: '1',

      //服务商商户appid
      //   fwsWxAppid: '',
      //服务商小程序appid
      fwsXcxAppid: '',
      //服务商小程序appsecret
      fwsXcxAppsecret: '',
      //   服务商小程序openid
      //   fwsXcxOpenId: '',
      //服务商商户号
      fwsMchId: '',
      //  服务商支付密钥
      fwsPrivateKey: '',

      // 服务商公众号appId”
      fwsGzhAppid: '',
      // 服务商公众号appsecret
      fwsGzhAppsecret: '',
      //服务商公众号openid
      //   fwsGzhOpenId: '',
      //服务商证书序列号
      fwsMerchantSerialNumber: '',
      //服务商子商户号
      fwsPtMchId: '',
      //   服务商支付v3密钥
      fwsV3Key: '',
      //服务商cert(证书)文件
      fwsCertFile: '',
      //服务商key文件
      fwsKeyFile: '',
      // 站点id
      siteId: this.$store.state.site.info.id
    };
    return {
      options: [],
      images: [],
      showEdit: false,
      isUpdata: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      formArr: [],
      // 日期范围输入
      dateRange: [],

      fileWxzfCertList: [],
      fileFwsfCertList: [],
      fileWxzfKeyList: [],

      fileFwsfKeyList: [],

      // 表单验证规则
      rules: {
        //   payType: [
        //     {
        //       required: true,
        //       message: '请填写支付类型',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfXcxAppid: [
        //     {
        //       required: true,
        //       message: '请输入微信支付小程序appid',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfXcxAppsecret: [
        //     {
        //       required: true,
        //       message: '请输入微信支付小程序appsecret',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfMchId: [
        //     {
        //       required: true,
        //       message: '请输入微信支付商户号',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfPrivateKey: [
        //     {
        //       required: true,
        //       message: '请输入微信支付密钥',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfGzhAppid: [
        //     {
        //       required: true,
        //       message: '请输入微信支付公众号appid',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfGzhAppsecret: [
        //     {
        //       required: true,
        //       message: '请输入微信支付公众号appsecret',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfV3Key: [
        //     {
        //       required: true,
        //       message: '请输入微信支付v3密钥',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfWxAppid: [
        //     {
        //       required: true,
        //       message: '请输入微信支付appid',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfMerchantSerialNumber: [
        //     {
        //       required: true,
        //       message: '请输入微信支付证书序列号',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfCertFile: [
        //     {
        //       required: true,
        //       message: '请输入微信支付cert(证书)文件',
        //       trigger: 'blur'
        //     }
        //   ],
        //   wxzfKeyFile: [
        //     {
        //       required: true,
        //       message: '请输入微信支付key文件',
        //       trigger: 'blur'
        //     }
        //   ],
        //   remitType: [
        //     {
        //       required: true,
        //       message: '请输入打款类型',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsWxAppid: [
        //     {
        //       required: true,
        //       message: '请输入服务商商户appid',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsXcxAppid: [
        //     {
        //       required: true,
        //       message: '请输入服务商小程序appid',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsXcxAppsecret: [
        //     {
        //       required: true,
        //       message: '请输入服务商小程序appsecret',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsMchId: [
        //     {
        //       required: true,
        //       message: '请输入服务商商户号',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsPrivateKey: [
        //     {
        //       required: true,
        //       message: '请输入服务商支付密钥',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsGzhAppid: [
        //     {
        //       required: true,
        //       message: '请输入服务商公众号appId',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsGzhAppsecret: [
        //     {
        //       required: true,
        //       message: '请输入服务商公众号appsecret',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsMerchantSerialNumber: [
        //     {
        //       required: true,
        //       message: '请输入服务商证书序列号',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsPtMchId: [
        //     {
        //       required: true,
        //       message: '请输入服务商子商户号',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsV3Key: [
        //     {
        //       required: true,
        //       message: '请输入服务商支付v3密钥',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsCertFile: [
        //     {
        //       required: true,
        //       message: '请输入服务商cert(证书)文件',
        //       trigger: 'blur'
        //     }
        //   ],
        //   fwsKeyFile: [
        //     {
        //       required: true,
        //       message: '请输入服务商key(证书)文件',
        //       trigger: 'blur'
        //     }
        //   ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  activated () {
    this.querys();
  },
  methods: {
    /* 保存编辑 */
    querys () {
      // 查询回显
      sitePayConfigDetail({
        siteId: this.form.siteId
      })
        .then((msg) => {
          console.log(msg);
          if (msg) {
            //   是修改
            this.$util.assignObject(this.form, {
              ...msg
            });
            this.form.id = msg.id;
            this.isUpdata = true;
            if (this.form.payType == 1) {


              if (msg.wxzfCertFile) {
                this.fileWxzfCertList = [{ name: msg.wxzfCertFile, url: msg.wxzfCertFile }]
              }
              //   fileFwsfCertList:[],
              if (msg.wxzfKeyFile) {
                this.fileWxzfKeyList = [{ name: msg.wxzfKeyFile, url: msg.wxzfKeyFile }]
              }

            } else {

              if (msg.fwsCertFile) {
                this.fileFwsfCertList = [{ name: msg.fwsCertFile, url: msg.fwsCertFile }]
              }
              if (msg.fwsKeyFile) {
                //   fileFwsfCertList:[],
                this.fileFwsfKeyList = [{ name: msg.fwsKeyFile, url: msg.fwsKeyFile }]
              }

            }
          } else {
            // 修改
            this.isUpdata = false;
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
      console.log('exceedFn')
    },
    exceedFn1 () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
      console.log('exceedFn1')
    },
    async handleFileChange (file, fileList, uploadFiles) {
      console.log(file, fileList);
      const res = await userOssSignature();
      console.log(res);
      let files = file.raw;
      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', date + suffix);
      param.append('policy', res.policy);
      param.append('OSSAccessKeyId', res.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', res.signature);
      param.append('file', files, files.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);
      let result = await axios.post(res.host, param, config);
      let url = res.host + '/' + date + suffix;
      console.log(url);
      if (url) {
        this.$message.success('上传成功')
      } else {
        this.$message.success('上传失败')
        return
      }
      // 如果是微信的调用微信的文件
      if (this.form.payType == '1') {
        if (uploadFiles == 'wxzfCertFile') {
          this.form.wxzfCertFile = url;
          this.fileWxzfCertList = [{ name: url, url: url }]

        } else {
          this.form.wxzfKeyFile = url;
          this.fileWxzfKeyList = [{ name: url, url: url }]
          // 		fileWxzfCertList: [],
          //   fileFwsfCertList: [],
          //   fileWxzfKeyList: [],
          //   fileFwsfKeyList: [],
        }
      } else {
        if (uploadFiles == 'fwsCertFile') {
          this.form.fwsCertFile = url;
          this.fileFwsfCertList = [{ name: url, url: url }]
        } else {
          this.form.fwsKeyFile = url;
          this.fileFwsfKeyList = [{ name: url, url: url }]
        }
      }
      this.imageUrl = url;

    },
    // 过滤文本
    filterText (e, form) {

      let privateKey = e.trim()
      let privateKeyPath = privateKey.replace(/^-----BEGIN PRIVATE KEY-----/, "").replace(/-----END PRIVATE KEY-----$/, "")
      console.log(privateKeyPath)
      if (form == 'wxForm') {
        this.form.fwsPrivateKey = privateKeyPath.trim();
      } else if (form == 'wxServiceForm') {
        this.form.wxzfPrivateKey = privateKeyPath.trim();
      }

    },
    handleRemove (e, type) {
      // this.e=[]
      console.log(e, type)
      console.log(this[type])

      this[type] = []
      if (type == 'fileWxzfCertList') {
        this.form.wxzfCertFile = '';
      } else {
        this.form.fwsCertFile = '';

      }


    },
    handleRemove2 (e, type) {

      console.log(e, type)
      console.log(this[type])
      this[type] = []
      if (type == 'fileWxzfKeyList') {
        this.form.wxzfKeyFile = '';
      } else {
        this.form.fwsKeyFile = '';
      }

    },
    save () {
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          const data = {
            ...this.form
          };
          console.log(data, this.isUpdata);
          const saveOrUpdate = this.isUpdata
            ? sitePayConfigModify
            : sitePayConfigsAdd;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.querys();
              this.$message.success('提交成功！');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          this.validMsg = ` 共有校验 ${Object.keys(obj).length} 项不通过`;
          return false;
        }
      });
    },
    addFoods () { },
    /* 更新visible */
    handleClose () {
      this.$emit('update:visible', false);
    }
  },
  watch: {
    visible (visible) {
      if (visible) {
        if (this.data) {
          this.$util.assignObject(this.form, this.data);
          this.isUpdate = true;
        } else {
          this.isUpdate = false;
        }
      } else {
        this.$refs['form'].clearValidate();
        this.form = { ...DEFAULT_FORM };
      }
    }
  }
};
</script>
<style lang="less" scoped>
.headerStyle {
  color: gray;

  margin-top: 5px;
}
</style>
